<template>
	<view>
		<view class="background"></view>
		<view class="body">
			<view class="">
				<view class="title">
					<view class="title-label">核销码</view>
					<view class="verification-code">{{reservationData.verificationCode || '-'}}</view>
				</view>
				<view class="service">
					<view>服务内容</view>
					<view class="service-item">
						<text class="label">维修方式：</text>
						<text>{{getServiceType(reservationData.type)}}</text>
					</view>
					<view class="service-item">
						<text class="label">维修状态：</text>
						<text>{{getServiceStatus(reservationData.status)}}</text>
					</view>
					<view class="service-item">
						<text class="label">店铺名称：</text>
						<text>{{getShopName(reservationData.shop)}}</text>
					</view>
				</view>
				<view class="orderInfo">
					<view>订单信息</view>
					<view>车主姓名：<text>{{reservationData.name || '-'}}</text></view>
					<view>联系电话：<text>{{reservationData.phone || '-'}}</text></view>
					<view>用户姓名：<text>{{getUserName(reservationData.user)}}</text></view>
					<view>预约时间：<text>{{reservationData.reservationTime || '-'}}</text></view>
					<view>提交时间：<text>{{reservationData.submitTime || '-'}}</text></view>
					<view>车牌号码：<text>{{reservationData.carNum || '-'}}</text></view>
					<view>车辆品牌：<text>{{(reservationData.carType && reservationData.carType.name) || '-'}}</text></view>
					<view>取车位置：<text>{{reservationData.location || '-'}}</text></view>
				</view>
			</view>
			<view class="btn" v-if="canVerify">
				<button @click="dialogToggle()">确认核销</button>
			</view>
			<view class="btn1" v-if="!canVerify">
				<button>已核销</button>
			</view>
			<!-- 弹出层 -->
			<view>
				<!-- 使用普通的模态框替代 uni-popup -->
				<view class="modal" v-if="showModal">
					<view class="modal-mask"></view>
					<view class="modal-content">
						<view class="modal-title">{{msgTitle}}</view>
						<view class="modal-body">{{msgContent}}</view>
						<view class="modal-footer">
							<button class="btn-cancel" @click="handleCancel">取消</button>
							<button class="btn-confirm" @click="handleConfirm">核销</button>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'scanVerification',
		data() {
			return {
				msgTitle: '核销此订单',
				msgContent: '请您仔细核对订单，此操作不可撤销，请谨慎操作！',
				isDistory: false,
				verificationCode: '',
				reservationData: {},
				showModal: false,
				isLoading: false,
				requestTimeout: 10000  // 10秒超时
			}
		},
		computed: {
			canVerify() {
				// 只有当状态为0或1，且未核销时才能显示核销按钮
				const status = String(this.reservationData.status);
				return ['0', '1'].includes(status) && !this.isDistory;
			}
		},
		onLoad(options) {
			if (options.verificationCode) {
				this.verificationCode = options.verificationCode;
				this.fetchReservationData();
			} else {
				uni.showToast({
					title: '缺少核销码',
					icon: 'none',
					duration: 2000,
					complete: () => {
						setTimeout(() => {
							uni.navigateBack();
						}, 2000);
					}
				});
			}
		},
		methods: {
			// 创建一个带超时的请求
			async timeoutRequest(requestPromise, timeout = this.requestTimeout) {
				// 创建一个会在指定时间后拒绝的 Promise
				const timeoutPromise = new Promise((_, reject) => {
					setTimeout(() => reject(new Error('请求超时')), timeout);
				});
				
				// 使用 Promise.race 竞争，谁先完成就返回谁的结果
				return Promise.race([requestPromise, timeoutPromise]);
			},
			// 获取预约数据
			fetchReservationData() {
				if (this.isLoading) return;
				this.isLoading = true;
				
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				
				this.$request({
					url: 'shop/reservation/reservation/list',
					method: 'GET',
					data: {
						verificationCode: this.verificationCode,
						del: 0,
						pageNum: 1,
						pageSize: 10
					},
					success: (res) => {
						console.log(res.data)
						if (res.data && res.data.rows && res.data.rows.length > 0) {
							this.reservationData = res.data.rows[0];
							// 如果状态为3，说明已核销
							if (this.reservationData.status === 3) {
								this.isDistory = true;
							}
						} else {
							uni.showToast({
								title: '未找到相关预约信息',
								icon: 'none',
								duration: 2000,
								complete: () => {
									setTimeout(() => {
										uni.navigateBack();
									}, 2000);
								}
							});
						}
					},
					fail: (error) => {
						uni.showToast({
							title: '数据加载失败',
							icon: 'none',
							duration: 2000
						});
					},
					complete: () => {
						this.isLoading = false;
						uni.hideLoading();
					}
				});
			},
			dialogToggle() {
				// 添加状态检查
				if (!this.canVerify) {
					uni.showToast({
						title: '当前状态不可核销',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				if (this.isLoading) return;
				this.showModal = true;
			},
			handleCancel() {
				this.showModal = false;
			},
			handleConfirm() {
				this.showModal = false;
				this.dialogConfirm();
			},
			// 确认核销
			dialogConfirm() {
				if (this.isLoading) return;
				if (!this.reservationData || !this.reservationData.id) {
					uni.showToast({
						title: '订单数据异常',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				this.isLoading = true;
				uni.showLoading({
					title: '核销中...',
					mask: true
				});
				
				// 先添加核销记录
				this.$request({
					url: 'shop/record/record',
					method: 'POST',
					data: {
						mid: this.reservationData.mid,
						oid: this.reservationData.id,
						name: this.reservationData.status ? '到店维修' : '上门取车',
						username: this.reservationData.user.name,
						time: this.formatDate(new Date()),
						del: '0'
					},
					success: (recordRes) => {
						if (recordRes.data && recordRes.data.code === 200) {
							// 记录添加成功，执行核销操作
							this.$request({
								url: 'shop/reservation/reservation',
								method: 'PUT',
								data: {
									id: this.reservationData.id,
									status: '2',
									del: 0
								},
								success: (verifyRes) => {
									if (verifyRes.data && verifyRes.data.code === 200) {
										this.isDistory = true;
										uni.showToast({
											title: '核销成功',
											icon: 'success',
											duration: 2000
										});
										this.fetchReservationData();
									} else {
										uni.showToast({
											title: verifyRes.data?.msg || '核销失败',
											icon: 'none',
											duration: 2000
										});
									}
								},
								fail: () => {
									uni.showToast({
										title: '核销失败',
										icon: 'none',
										duration: 2000
									});
								},
								complete: () => {
									this.isLoading = false;
									uni.hideLoading();
									this.showModal = false;
								}
							});
						} else {
							uni.showToast({
								title: '核销记录添加失败',
								icon: 'none',
								duration: 2000
							});
							this.isLoading = false;
							uni.hideLoading();
							this.showModal = false;
						}
					},
					fail: () => {
						uni.showToast({
							title: '核销记录添加失败',
							icon: 'none',
							duration: 2000
						});
						this.isLoading = false;
						uni.hideLoading();
						this.showModal = false;
					}
				});
			},
			// 格式化日期
			formatDate(date) {
				const pad = (num) => String(num).padStart(2, '0');
				return date.getFullYear() + '-' +
					pad(date.getMonth() + 1) + '-' +
					pad(date.getDate()) + ' ' +
					pad(date.getHours()) + ':' +
					pad(date.getMinutes()) + ':' +
					pad(date.getSeconds());
			},
			// 获取店铺名称
			getShopName(shop) {
				return shop && shop.name ? shop.name : '-';
			},
			// 获取用户名称
			getUserName(user) {
				return user && user.name ? user.name : '-';
			},
			// 获取维修方式文本
			getServiceType(type) {
				const typeMap = {
					'0': '到店维修',
					'1': '上门取车'
				};
				return typeMap[type] || '-';
			},
			// 获取维修状态文本
			getServiceStatus(status) {
				const statusMap = {
					'0': '已预约',
					'1': '进行中',
					'2': '已完成',
					'3': '已取消订单'
				};
				return statusMap[String(status)] || '-';
			},
			// 检查是否可以核销
			checkVerifyStatus() {
				const status = String(this.reservationData.status);
				if (!['0', '1'].includes(status)) {
					this.isDistory = true;
				}
			}
		}
	}
</script>

<style>
	page{
		background-color: #f0f0f0;
		padding: 0 20rpx;
	}
	.background {
		width: 750rpx;
		height: 280rpx;
		background-color: #2979ff;
		margin-left: -20rpx;
	}
	.body{
		position: absolute;
		top: 20rpx;
	}
	.body > view:nth-child(1){
		padding: 0 20rpx;
		width: 710rpx;
		background-color: white;
		border-radius: 20rpx;
		box-sizing: border-box;
	}
	.title {
		width: 100%;
		padding: 20rpx 0;
		text-align: center;
		color: black;
	}
	.title-label {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
	.verification-code {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		word-break: break-all;
		padding: 0 30rpx;
		line-height: 1.4;
	}
	/* 服务内容样式 */	
	.service {
		border-top: 4rpx solid #e9e9eb;
		border-bottom: 4rpx solid #e9e9eb;
		padding: 20rpx 0;
	}
	.service-item {
		display: flex;
		height: 50rpx;
		line-height: 50rpx;
		font-size: 28rpx;
		color: #333;
	}
	.service-item .label {
		width: 160rpx;
		color: #666;
	}
	
	/* 订单信息样式 */
	.orderInfo {
		padding: 20rpx 0;
	}
	.orderInfo > view:nth-child(1){
		font-size: 34rpx;
		margin-bottom: 10rpx;
		color: black;
	}
	.orderInfo > view {
		height: 50rpx;
		line-height: 50rpx;
		font-size: 28rpx;
		color: #333;
	}
	.orderInfo > view text {
		color: #666;
	}
	/* 核销按钮样式 */
	.btn{
		margin-top: 50rpx;
	}
	.btn > button{
		width: 400rpx;
		height: 60rpx;
		line-height: 60rpx;
		border-radius: 30rpx;
		background-color: #2979ff;
		color: white;
		font-size: 30rpx;
	}
	.btn1 > button{
		margin-top: 50rpx;
		width: 400rpx;
		height: 60rpx;
		line-height: 60rpx;
		border-radius: 30rpx;
		border-radius: 30rpx;
		background-color: #909399;
		color: white;
		font-size: 30rpx;
	}
	
	/* 模态框样式 */
	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
	}
	
	.modal-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
	}
	
	.modal-content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		background: #fff;
		border-radius: 10rpx;
		overflow: hidden;
	}
	
	.modal-title {
		padding: 30rpx;
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		border-bottom: 1px solid #eee;
	}
	
	.modal-body {
		padding: 40rpx 30rpx;
		text-align: center;
		font-size: 28rpx;
		color: #666;
	}
	
	.modal-footer {
		display: flex;
		border-top: 1px solid #eee;
	}
	
	.modal-footer button {
		flex: 1;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 30rpx;
		border: none;
		border-radius: 0;
		background: #fff;
	}
	
	.btn-cancel {
		color: #666;
		border-right: 1px solid #eee;
	}
	
	.btn-confirm {
		color: #2979ff;
	}
</style>
